import { _decorator, Animation, AudioSource, CCFloat, Component, instantiate, Label, Node, ParticleSystem2D, tween } from 'cc';
import { ClickRotate } from './ClickRotate';
import { MigaManager } from '../MigaManager';
const { ccclass, property } = _decorator;

@ccclass('ClickUse')
export class ClickUse extends Component {

    @property(Node)
    target: Node;

    @property(Node)
    particle: Node;

    @property(Node)
    spawn: Node;

    @property(Node)
    point: Node;

    @property(AudioSource)
    audio: AudioSource;

    @property(Animation)
    ani: Animation;

    @property
    aniStr = "";

    @property
    min = 0;

    @property
    max = 99;

    isAni = false;

    Click() {
        if (this.getComponent(ClickRotate)?.isTween) return;
        this.target.active = !this.target.active;
        if (this.audio) {
            if (this.target.active) this.audio.play();
            else this.audio.stop();
        }
        if (this.particle) {
            let particles = this.particle.getComponentsInChildren(ParticleSystem2D);
            for (let i = 0; i < particles.length; i++) {
                const element = particles[i];
                if (this.target.active) element.resetSystem();
                else element.stopSystem();
            }
        }
    }

    PlayAni() {
        if (this.isAni) {
            this.ani.play();
            this.audio.stop();
        }
        else {
            this.ani.play(this.aniStr);
            this.audio.play();
        }
        this.isAni = !this.isAni;
    }

    ClickNumPlus() {
        let label = this.node.getComponent(Label);
        let num = parseInt(label.string);
        if (num < 99) num++;
        else num = 0;
        label.string = num < 10 ? ("0" + num) : num.toString();
    }

    ClickAniSpeed() {
        this.ani.getState(this.ani.defaultClip.name).speed = this.ani.getState(this.ani.defaultClip.name).speed == 1 ? 5 : 1;
    }

    SubStrNum() {
        if (!this.target.active) return;
        let label = this.target.getComponent(Label);
        let num = parseInt(label.string);
        if (num > this.min) num--;
        label.string = num.toString();
    }

    AddStrNum() {
        if (!this.target.active) return;
        let label = this.target.getComponent(Label);
        let num = parseInt(label.string);
        if (num < this.max) num++;
        label.string = num.toString();
    }

    Spawn() {
        let node = instantiate(this.spawn);
        node.setParent(MigaManager.Instance.touchPanel);
        node.setWorldPosition(this.point.getWorldPosition());
        node.active = true;
    }
}


